
{% extends "tj3/tj3.html" %}

{% block navigation %}
<script type="text/javascript">
    // http://www.prodevtips.com/2010/03/07/jquery-drag-and-drop-to-sort-tree/      
    function parseTree(ul){
        var tags = [];
        ul.children("li").each(function(){
            var subtree = $(this).children("ul");
            var me=$(this).attr('id');
            if(subtree.size() > 0)
                tags.push({'root':me, 'children':parseTree(subtree)});
            else
                tags.push(me);
            });
        return tags;
    }
	
	function taskEdit(task_id,offset){	
		$.post("{% url task_edit %}",
		{'id': task_id},
		function(resp_data){
		
		// Read task info
		var task = $.parseJSON(resp_data['task']);
		$('#task_id').val(task_id);
		$('#task_name').val(task[0]['fields']['name']);
		$('#task_parent').val(task[0]['fields']['parent']);
		$('textarea[name=task_description]').val(task[0]['fields']['description']);
		
		// Read period info
		var period=$.parseJSON(resp_data['period']);
		if (period.length>0){
        	$('#start').val(period[0]['fields']['start']);
        	$('#end').val(period[0]['fields']['end']);
        	$('#duration').val(period[0]['fields']['duration']);
        	$('#length').val(period[0]['fields']['length']);
        	$('#effort').val(period[0]['fields']['effort']);
        	$('#max_start').val(period[0]['fields']['max_start']);
        	$('#min_start').val(period[0]['fields']['min_start']);
        	$('#max_end').val(period[0]['fields']['max_end']);
        	$('#min_end').val(period[0]['fields']['min_end']);
		}
		else{
        	$('#start').val('');
        	$('#end').val('');
        	$('#duration').val('');
        	$('#length').val('');
        	$('#effort').val('');
        	$('#max_start').val('');
        	$('#min_start').val('');
        	$('#max_end').val('');
        	$('#min_end').val('');
		}
		
		$('#start').datepicker({ dateFormat: 'yy-mm-dd' });
		$('#end').datepicker({ dateFormat: 'yy-mm-dd' });
		$('#max_start').datepicker({ dateFormat: 'yy-mm-dd' });
		$('#min_start').datepicker({ dateFormat: 'yy-mm-dd' });
		$('#max_end').datepicker({ dateFormat: 'yy-mm-dd' });
		$('#min_end').datepicker({ dateFormat: 'yy-mm-dd' });
		
		// Read dependency
		var deps=resp_data['deps'];
		var dd=[];
		for (var key in deps) {
        	dd.push(deps[key]);
		}
		$('#deps').val(dd.join(','));
		
		// Update resource_link
		$('#resource_allocation_link').attr('href',['/mysite/tj3/resource/allocate',task_id].join('/'));
								                                		
		// Show task record div
		$('#task_info').offset(offset).css('z-index',999).show();
     });// end of post
     }	

    $(document).ready(function(){
    	var oTableDnD;
		var oTable=$('#datatable').dataTable({
		"sAjaxSource": "{% url task_datatable_json project.id project.scenario.id %}",
		"iDisplayLength": 200,
		"aoColumns": [
			{ "mDataProp": "id" },
			{ "mDataProp": "wbs" },
			{ "mDataProp": "name" },
			{ "mDataProp": "desc" },
			{ "mDataProp": "start" },
			{ "mDataProp": "end" },
			{ "mDataProp": "length" },
			{ "mDataProp": "duration" },
			{ "mDataProp": "effort" },
			{ "mDataProp": "max_start" },
			{ "mDataProp": "min_start" },
			{ "mDataProp": "max_end" },
			{ "mDataProp": "min_end" },
			{ "mDataProp": "milestone" },
			{ "mDataProp": "deps" },
			{ "mDataProp": "ars" } 				
		],
		"aoColumnDefs": [ 
		{ "bSearchable": false, "bVisible": true, "aTargets": [ 0 ] },
		{ "bSearchable": false, "bVisible": true, "aTargets": [ 1 ] }
		],
		
		"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
			$(nRow).attr('id',aData.id);
        },
		"fnInitComplete": function(oSettings, json) {
			$('table#datatable tbody td').click(function(){ 
				var aPos=oTable.fnGetPosition(this);
				var id=oTable.fnGetData(aPos[0],0);
				var offset=$(this).offset();
				taskEdit(id,{'top':offset.top,'left':offset.left+$(this).outerWidth()});
        	});
        	
			oTableDnD=$('table#datatable').tableDnD({
        	});		
        }		
		});

    $('#save_btn').button().click(function(){
    	var tt=$('#datatable').tableDnDSerialize();
    	console.log(tt);
    	
        var a = $.toJSON(parseTree($("#task_tree")));
        $.post("{% url task_move %}", 
            {'data':JSON.stringify(a)},
            function(data) {
                alert('Hierarchy Saved!');
            }
        );
    });// end of click func
    
         
        $("li.tree_item span").droppable({
                tolerance        : "pointer",
                hoverClass        : "tree_hover",
                drop            : function(event, ui){
                        var dropped = ui.draggable;
                        dropped.css({top: 0, left: 0});
                        var me = $(this).parent();
                        
                        // if we are dropping to self, do nothing.
                        if(me == dropped)
                                return;
                                
                                
                        var subbranch = $(me).children("ul");
                        if(subbranch.size() == 0) {
                                me.find("span").after("<ul><\/ul>");
                                subbranch = me.find("ul");
                        }
                
                        var oldParent = dropped.parent();
                        subbranch.eq(0).append(dropped);
                        var oldBranches = $("li", oldParent);
                        if (oldBranches.size() == 0) { $(oldParent).remove(); }
                }// end of function for "drop"
        });

        $("li.tree_item").draggable({
                opacity: 0.5,
                revert: true
        });
        
        $('li.tree_item span').click(function(){
            // Remove all span selected class
            $('span.selected').removeClass('selected');
        
            // give this item a color
            $(this).addClass("selected");
        
        var task_id=$(this).attr('title');              
     	var task_offset=$(this).offset();
     			   
        taskEdit(task_id,task_offset);                
        });

    
       $('#mymodal').hide();
                        
        $('#task_info').hide();
        $('#advanced_option').hide();
        $('#show_advanced_option').click(function(){
                $('#advanced_option').toggle();
        });             

        $('#update_btn').button().click(function(){
                $('form').get(0).setAttribute('action', '{% url task_update 0 %}');
        });
        
        $('#clone_btn').button().click(function(){
                $('form').get(0).setAttribute('action', '{% url task_update 1 %}');
        });
        
        $('#delete_btn').button().click(function(){
                var task_id=$('#task_id').val();
                $('form').get(0).setAttribute('action', '/mysite/tj3/task/delete/' + task_id+'/');
        });

        $('#split_btn').button().click(function(){
                var task_id=$('#task_id').val();
                $('form').get(0).setAttribute('action', '/mysite/tj3/task/split/' + task_id+'/');
        });

        $('#create_task').click(function(){
                $("#mymodal").modal({
                        opacity:80,
                        overlayCss: {backgroundColor:"#fff"}
                });
        });
        
        $('#task_info_cancel_btn').button().click(function(){
            $('#task_info').hide();
        });
        
        $("#import_mpp").hide();
        $('#import_mpp_link').click(function(){
                $("#import_mpp").modal({
                        opacity:80,
                        overlayCss: {backgroundColor:"#fff"}
                });
                $('#import_mpp_btn').button().click(function(){
                });
        });
        
        $('#create_btn').click(function(){
                var proj_id;
                var name;
                var description;
                
                proj_id=$('#mymodal').find('.project').text();
                
                name=$('#name').val();
                description=$('textarea[name=description]').val();
                
                // Post the new event to the server!
                var json_event=$.toJSON({'proj_id':proj_id, 'name':name, 'description':description});
                $.post("{% url task_create %}",
                {'data':json_event},
                function (data){
                        //alert(data);
                        new_url = ['/mysite/tj3/task/display',{{project.id}}].join('/'); 
                        window.location.replace(new_url);
                });             
        });
        
                                
        });                     

        $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                        if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                        // Only send the token to relative URLs i.e. locally.
                        xhr.setRequestHeader("X-CSRFToken",
                        $('input[name="csrfmiddlewaretoken"]').val());
                        }
                }        	
        });// end of $(document).ready
        
    </script>
{% endblock navigation %} 
    
{% block content %}

    <h1 class="ui-widget ui-widget-header">{{project.name}}
    <span class="float_right">Manage Task Hierarchy</span></h1>

    <div>
            You can drag and drop the tasks to rearrange their
            hierarchy. However, this should be done with extreme
            caution since moving a task can easily break other
            dependencies that have been assigned to this task.<br>
            <br>
        </div>After you are satisfied with the new hierarchy, click
        <span id="save_btn">Save Hierarchy</span>.<br>

        <h2 class="ui-state-highlight ui-corner-all">Task Hierarchy</h2>

        <table>
            <tr>
                <td>      
                {% load mptt_tags %}   
                <div class ="mycontent">
                        <ul class="tree_item" id="task_tree">
                                {% csrf_token %}                
                        {% recursetree tasks %}
                        <li class="tree_item" id="{{node.id}}">
                        <!--- dump node information --->
                        &mdash;&nbsp;
                        <span title="{{node.id}}">
                        <b style="background-color:yellow;color:black;">{{node.wbs}}</b> {{node.id}} {{ node.name }}
                        </span>
                        <!--- drill down to the next level --->
                        {% if not node.is_leaf_node %}
                        	<ul class="children">
                                {{ children }}
                            </ul>
                        {% endif %}
                        </li>
                        {% endrecursetree %}
                        </ul>
                </div>
                </td>

                <td>
                    <div id="task_info" class="mycontent">
						<div id="create_task" class="fancy">
							<span class="float_right ui-icon ui-icon-plusthick"></span>
							Create More Tasks
							</div>

                        <form id="update_form" action="" method=
                        "post" enctype="multipart/form-data" name=
                        "update_form">
                            {% csrf_token %}

                            <div>
                                <input id=
                                "task_id" type="hidden" name=
                                "task_id" value="" readonly>

                                <table>
                                    <!--- task name =-->

                                    <tr>
                                        <td>Name:</td>

                                        <td><input id="task_name"
                                        type="text" name=
                                        "task_name" value=""></td>
                                    </tr>

                                    <tr>
                                        <td>Description:</td>

                                        <td>
                                        <textarea name=
                                        "task_description" rows="5"
                                        cols="20">
										</textarea>
										</td>
                                    </tr>

                                    <tr>
                                        <td>Parent Task:</td>

                                        <td><input id="task_parent"
                                        type="text" name=
                                        "task_parent" value=""><br>
                                        <!--- period =--></td>
                                    </tr>

                                    <tr>
                                        <td>Start:</td>

                                        <td><input id="start" type=
                                        "text" name="start" value=
                                        ""></td>
                                    </tr>

                                    <tr>
                                        <td>End:</td>

                                        <td><input id="end" type=
                                        "text" name="end" value=
                                        ""></td>
                                    </tr>

                                    <tr>
                                        <td>Dependency:</td>

                                        <td><input id="deps" type=
                                        "text" name="deps" value=
                                        ""></td>
                                    </tr>

                                    <tr>
                                        <td>Duration:</td>

                                        <td><input id="duration"
                                        type="text" name="duration"
                                        value=""></td>
                                    </tr>

                                    <tr>
                                        <td>Length:</td>

                                        <td><input id="length"
                                        type="text" name="length"
                                        value=""></td>
                                    </tr>

                                    <tr>
                                        <td>Effort:</td>

                                        <td><input id="effort"
                                        type="text" name="effort"
                                        value=""><br>
                                        <a id=
                                        "resource_allocation_link"
                                        href="" 
                                        name=
                                        "resource_allocation_link">
                                        To assign
                                        resources...</a></td>
                                    </tr>
                                </table>
                                <span id=
                                'show_advanced_option' class=
                                "fancy" name=
                                "show_advanced_option">Advanced
                                Options...</span>

                                <div id='advanced_option' stype=
                                "display:none;">
                                    <table>
                                        <tr>
                                            <td>Max Start:</td>

                                            <td><input id=
                                            "max_start" type="text"
                                            name="max_start" value=
                                            ""></td>
                                        </tr>

                                        <tr>
                                            <td>Min Start:</td>

                                            <td><input id=
                                            "min_start" type="text"
                                            name="min_start" value=
                                            ""></td>
                                        </tr>

                                        <tr>
                                            <td>Max End:</td>

                                            <td><input id="max_end"
                                            type="text" name=
                                            "max_end" value=
                                            ""></td>
                                        </tr>

                                        <tr>
                                            <td>Min End:</td>

                                            <td><input id="min_end"
                                            type="text" name=
                                            "min_end" value=
                                            ""></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            <input id="update_btn" type=
                            "submit" value="Update"> 
                            <input id=
                            "clone_btn" type="submit" value="Clone"> 
                            <input id="split_btn" type=
                            "submit" value="Split"> 
                            <input id=
                            "delete_btn" type="submit" value="Delete">
                            <span id="task_info_cancel_btn">Cancel</span>
                        </form>
                    </div>
                </td>
            </tr>
        </table>

        <h2 class="ui-state-highlight ui-corner-all">Tasks</h2>
		<table id="datatable">
		<thead>
		<tr><th>ID
			<th>WBS
			<th>Name
			<th>Description
			<th>Start
			<th>End
			<th>Length
			<th>Duration
			<th>Effort
			<th>Max Start
			<th>Min Start
			<th>Max End
			<th>Min End
			<th>Is Milestone?
			<th>Dependencies
			<th>Resources
		</tr>
		</thead>
		<tbody>
		</tbody>
		</table>

    <div>
	<div class="ui-state-highlight ui-corner-all">Go To</div>
		<ul>
			<li><a href="{% url home %}"><b>Home</b></a>
			<li><a href="{% url report_manage project.id %}">Build User Reports</a>
            <li><a href={% url import_freemind %} title="import freemind">Import Task From Freemind XML</a></li>
            
            <li><span id="import_mpp_link">
            	Import Task From Microsoft Project (MPP) XML</span>
            </li>
			<li>Execution Central
			<ul>
				{% for s in scenarios %}
				<li><a href="{% url project_main_actual project.id, s.id %}">
				<font color=blue>{{s.name|capfirst}}</font>
				</a>
				{% endfor %}
			</ul>
		</ul>
	</div>
    </div>


    <div id="mymodal" style="color:white;">
        <span class="project" hidden="">{{project.id}}</span>
        <label>Name</label><br>
        <input id="name" type="text" value=""><br>
        <label>Description</label><br>
        <textarea name="description" rows="5" cols="20">
</textarea><br>

        <div class="float_right">
            <input type="button" id="create_btn" value="Create"
            class="simplemodal-close"> <input type="button" id=
            "cancel_btn" value="Cancel" class="simplemodal-close">
        </div>
    </div>

<div id="import_mpp" style="color:white;">
	<span class="project" hidden>{{project.id}}</span>

	<form action="." method="post" enctype="multipart/form-data">
		<label>Select the Microsoft Project XML file:</label>
			{{ form }}
		<input type="submit" id="import_mpp_btn">Import</input>
	</form>  
</div>

{% endblock content %}

